package blue.base.internal.core.security;

import blue.base.core.security.KeyPairMode;

import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author Jin Zheng
 * @since 1.0 2022-01-27
 */
public class LoadEncodedKeyPair extends AbstractKeyPair {
	private final String algorithm;
	private final byte[] pubEncoded;
	private final byte[] privEncoded;

	public LoadEncodedKeyPair(KeyPairMode mode, byte[] pubEncoded, byte[] privEncoded) {
		this.algorithm = mode.getKey();
		this.pubEncoded = pubEncoded;
		this.privEncoded = privEncoded;
		this.init();
	}

	public LoadEncodedKeyPair(KeyPairMode mode, String pubBase64, String privBase64) {
		this(mode, decodeBase64(pubBase64), decodeBase64(privBase64));
	}

	private static byte[] decodeBase64(String base64) {
		if (base64 == null || base64.isEmpty()) {
			return null;
		}
		return Base64.getDecoder().decode(base64);
	}

	private void init() {
		var pubKeySpec = new X509EncodedKeySpec(pubEncoded);
		var privKeySepc = new PKCS8EncodedKeySpec(privEncoded);

		try {
			var factory = KeyFactory.getInstance(algorithm);
			this.publicKey = factory.generatePublic(pubKeySpec);
			this.privateKey = factory.generatePrivate(privKeySepc);
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}

}
